package com.wcfsy.wechat.wx.entity;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.wcfsy.wechat.wx.util.Constant;
import com.wcfsy.wechat.wx.util.HttpClientUtil;
import com.wcfsy.wechat.wx.util.HttpUtil;
import com.wcfsy.wechat.wx.util.JsonMessage;

public class WechatMenuUtil {

	public static WechatMenu getWechatMenu(JSONObject jsonObject) {
		WechatMenu menu = new WechatMenu();
		if (jsonObject.containsKey("type")) {
			menu.setType(jsonObject.getString("type"));
		}
		if (jsonObject.containsKey("name")) {
			menu.setText(jsonObject.getString("name"));
		}
		if (jsonObject.containsKey("url")) {
			menu.setUrl(jsonObject.getString("url"));
		}
		return menu;
	}

	/**
	 * 向微信平台提交json字符串
	 */
	public static JsonMessage submitWechatMenuJson(String access_token,
			String jsonMenu) throws Exception {
		String deleteResult = HttpClientUtil.get(Constant.DELETE_MENU
				+ access_token);
		JSONObject deleteObject = JSONObject.parseObject(deleteResult);
		if (deleteObject.getInteger("errcode") == 0) {
			String menuUrl = Constant.WX_MENU + access_token;
			String result = HttpUtil.getInstance().phpPost(menuUrl,
					JSONObject.parseObject(jsonMenu));
			if (StringUtils.isNotEmpty(result)) {
				JSONObject meunResult = JSONObject.parseObject(result);
				int code = meunResult.getInteger("errcode");
				if (code == 0) {
					return JsonMessage.getSuccessJson("生成菜单成功");
				} else {
					return JsonMessage.getErrorJson("生成菜单失败");
				}
			} else {
				return JsonMessage.getErrorJson("微信接口失败");
			}
		} else {
			return JsonMessage.getErrorJson("微信菜单删除失败");
		}
	}

}
